<template>
  <div class="container">
    <el-dialog
      :visible.sync="formVisible"
      append-to-body
      :close-on-click-modal="false"
      title="实名认证"
      width="900px"
    >
      <el-form ref="dataForm" :model="postData" :rules="rules" label-width="180px">

        <el-form-item label="身份证人像面">
          <el-row :gutter="30">
            <el-col :span="11">
              <div class="grid-content">
                <el-upload
                  ref="id_card_z"
                  class="upload-demo"
                  accept="image/png, image/jpeg"
                  name="imgPath"
                  :with-credentials="true"
                  :headers="token"
                  :action="imgUploadAPI"
                  :before-upload="beforeAvatarUpload"
                  :on-success="handleSuccess"
                  :before-remove="beforeRemove"
                  :on-remove="handleRemoveFront"
                  :limit="1"
                  :on-exceed="handleExceed"
                  list-type="picture"
                >
                  <el-button size="small" type="primary" @click="uploadSign=1">选取文件</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
                </el-upload>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content">
                <img class="show-img" src="@/assets/img/id_card_z.png" alt="样图">
              </div>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="身份证国徽面">
          <el-row :gutter="30">
            <el-col :span="11">
              <div class="grid-content">
                <el-upload
                  ref="id_card_f"
                  class="upload-demo"
                  accept="image/png, image/jpeg"
                  name="imgPath"
                  :with-credentials="true"
                  :headers="token"
                  :action="imgUploadAPI"
                  :before-upload="beforeAvatarUpload"
                  :on-success="handleSuccess"
                  :before-remove="beforeRemove"
                  :on-remove="handleRemoveReverse"
                  :limit="1"
                  :on-exceed="handleExceed"
                  list-type="picture"
                >
                  <el-button size="small" type="primary" @click="uploadSign=2">选取文件</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
                </el-upload>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content">
                <img class="show-img" src="@/assets/img/id_card_f.png" alt="样图">
              </div>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="手持身份证">
          <el-row :gutter="30">
            <el-col :span="11">
              <div class="grid-content">
                <el-upload
                  ref="avatar"
                  class="upload-demo"
                  accept="image/png, image/jpeg"
                  name="imgPath"
                  :with-credentials="true"
                  :headers="token"
                  :action="imgUploadAPI"
                  :before-upload="beforeAvatarUpload"
                  :on-success="handleSuccess"
                  :before-remove="beforeRemove"
                  :on-remove="handleRemoveHand"
                  :limit="1"
                  :on-exceed="handleExceed"
                  list-type="picture"
                >
                  <el-button size="small" type="primary" @click="uploadSign=3">选取文件</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
                </el-upload>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content">
                <img class="show-img" src="@/assets/img/avatar.png" alt="样图">
              </div>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="真实姓名" prop="name">
          <el-input v-model="postData.name" type="text" placeholder="请输入身份证上的姓名" autofocus="" />
        </el-form-item>
        <el-form-item label="身份证号" prop="id_card_num">
          <el-input v-model="postData.id_card_num" type="text" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="postData.phone" type="text" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="submitForm('dataForm')">立即提交</el-button>
          <el-button @click="resetForm('dataForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import realCUD from '@/api/system/real'
export default {
  name: 'RealAdd',
  data() {
    return {
      formVisible: false,
      // 多个上传组件标记  1 身份证正面；2 身份证背面；3 省份证SIM卡手持
      uploadSign: null,
      // 图片上传接口
      imgUploadAPI: '//127.0.0.1/admin/file/upload_img',
      loading: false,
      // 信息提交数据
      postData: {
        /**
         * name 姓名
         * phone 手机号码
         * id_card_num 证件号  身份证号
         * id_card_z 身份证正面
         * id_card_f 身份证反面
         * avatar 手持身份证
         */
        name: '',
        phone: '',
        id_card_num: '',
        id_card_z: '',
        id_card_f: '',
        avatar: ''
      },
      handleSubmit: 'add',
      token: null,
      // 表单定义验证规则   trigger 为触发条件 http://element-cn.eleme.io/#/zh-CN/component/form#biao-dan-yan-zheng   官网地址
      rules: {
        // 姓名
        name: [{ required: true, message: '请输入员工姓名', trigger: 'blur' }],
        // 手机号码
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          {
            validator: function(rule, value, callback) {
              var MobileRegex = /^(13[0-9]|147|15[0-9]|17[0-9]|18[0-9])\d{8}$/
              if (!MobileRegex.test(value)) {
                callback(new Error('手机号码格式不正确！'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        // 身份证号
        id_card_num: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          {
            validator: function(rule, value, callback) {
              var MobileRegex = /(^\d{18}$)|(^\d{17}(\d|X|x)$)/
              if (!MobileRegex.test(value)) {
                callback(new Error('身份证号格式不正确！'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {
    formVisible: function(newVal, oldVal) {
      if (newVal === true) {
        if (this.handleSubmit === 'add') {
          this.initForm()
        } else {
          this.getRealInfo()
        }
      }
    }
  },
  created() {
    this.token = { 'token': getToken() }
  },
  methods: {
    initForm: function() {
      // 赋值表单
      this.postData = {
        name: '',
        phone: '',
        id_card_num: '',
        id_card_z: '',
        id_card_f: '',
        avatar: ''
      }
      if (this.$refs.id_card_z) {
        this.$refs.id_card_z.clearFiles()
        this.$refs.id_card_f.clearFiles()
        this.$refs.avatar.clearFiles()
      }
    },
    // 上传文件之前的钩子，参数为上传的文件，若返回 false 或者返回 Promise 且被 reject，则停止上传。
    beforeAvatarUpload: function(file) {
      // 判断上传文件类型
      const me = this
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      if (!(isJPG || isPNG)) {
        me.$message.error('上传的文件只能是 JPG 或者是 PNG 格式的')
      }
    },
    // 文件超出个数限制时的钩子
    handleExceed(file, fileList) {
      const me = this
      me.$message.warning('只能上传一个文件')
    },
    // 文件上传成功时的钩子
    handleSuccess(res, file) {
      const me = this
      const sign = me.uploadSign
      // 判断接口返回的 code 是否为  0    0 代表成功
      if (res.code === 0) {
        // 通过 sign 判断给相应的字段赋值
        if (sign === 1) {
          // 正面
          me.postData.id_card_z = res.data[0]
        } else if (sign === 2) {
          // 背面
          me.postData.id_card_f = res.data[0]
        } else if (sign === 3) {
          // 手持
          me.postData.avatar = res.data[0]
        }
      } else {
        // 失败回调
        me.$message.error(`${res.info}`)
        // 通过 sign 判断清空相应的列表 因为默认会显示出图片其实是失败了，容易造成用户误解
        if (sign === 1) {
          // 正面
          me.$refs.id_card_z.clearFiles()
        } else if (sign === 2) {
          // 背面
          me.$refs.id_card_f.clearFiles()
        } else if (sign === 3) {
          // 手持
          me.$refs.avatar.clearFiles()
        }
      }
      // 清空标记
      me.uploadSign = null
    },
    // 删除文件之前的钩子，参数为上传的文件和文件列表，若返回 false 或者返回 Promise 且被 reject，则停止上传。
    beforeRemove(file, fileList) {
      // 增加一个询问框
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    // 文件列表移除文件时的钩子 因为是三个组件所以便分开写了三个方法，写成一个带参数的试过了不行
    handleRemoveFront(file, fileList) {
      const me = this
      me.postData.id_card_z = ''
    },
    handleRemoveReverse(file, fileList) {
      const me = this
      me.postData.id_card_f = ''
    },
    handleRemoveHand(file, fileList) {
      const me = this
      me.postData.avatar = ''
    },
    // 提交数据
    submitForm(formName) {
      const that = this
      this.$refs[formName].validate(valid => {
        // 通过插件自定义全部规则已验证通过
        if (valid) {
          if (!that.postData.id_card_z) {
            that.$message.error('请上传您的身份证正面图片')
            return false
          }
          if (!that.postData.id_card_f) {
            that.$message.error('请上传您的身份证反面图片')
            return false
          }
          if (!that.postData.avatar) {
            that.$message.error('请上传您的身份证手持图片')
            return false
          }
          that.loading = true
          // 添加操作
          if (that.handleSubmit === 'add') {
            realCUD.add(that.postData).then(res => {
              that.loading = false
              if (res.code === 0) {
                this.$notify({
                  title: '操作完成！',
                  type: 'success'
                })
                // 返回一个状态表示已进行身份验证
                that.$emit('status', 1)
                that.formVisible = false
              }
            }).catch(res => {
              this.loading = false
            })
          } else {
            // 保存修改
            realCUD.edit(that.postData).then(res => {
              that.loading = false
              if (res.code === 0) {
                this.$notify({
                  title: '操作完成！',
                  type: 'success'
                })
                // 返回一个状态表示已进行身份验证
                that.$emit('status', 1)
                that.formVisible = false
              }
            }).catch(res => {
              this.loading = false
            })
          }
        } else {
          return false
        }
      })
    },
    // 获取已提交认证的信息
    getRealInfo() {
      var that = this
      realCUD.find().then(res => {
        if (res.code === 0) {
          if (!res.data) {
            this.$notify({
              title: '认证数据不存在',
              type: 'error'
            })
            return
          }
          // 赋值表单
          that.postData = {
            name: res.data.name,
            phone: res.data.phone,
            id_card_num: res.data.id_card_num,
            id_card_z: '',
            id_card_f: '',
            avatar: ''
          }
          this.$refs.id_card_z.clearFiles()
          this.$refs.id_card_f.clearFiles()
          this.$refs.avatar.clearFiles()
        }
      }).catch(err => {
        console.log('error:' + err)
      })
    },
    // 重置表单
    resetForm(formName) {
      const that = this
      this.$refs[formName].resetFields()
      // 清空上传的文件
      // 正面
      that.$refs.id_card_z.clearFiles()
      // 背面
      that.$refs.id_card_f.clearFiles()
      // 手持
      that.$refs.avatar.clearFiles()
      that.postData.id_card_z = ''
      that.postData.idid_card_f = ''
      that.postData.avatar = ''
    }
  }
}
</script>

<style lang="scss">
body {
  .container {
    form {
      width: 700px;
      margin: 0 auto;
      .show-img {
        width: 300px;
        max-width: 100%;
      }
    }
  }
}
</style>
